<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
      <el-steps :active="stepactive - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form ref="baseInfoRef" :model = "baseInfo" :rules="baseInfoRules" label-position="top" >
        <el-tabs v-model="stepactive" tab-position='left' :before-leave="beforeTabsleave" @tab-click="getParamsList">
          <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="baseInfo.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price" type="number">
            <el-input v-model="baseInfo.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight" type="number">
            <el-input v-model="baseInfo.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number" type="number">
            <el-input v-model="baseInfo.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader v-model="baseInfo.goods_cat" :options="CataList" :props="params" @change="CataChange"></el-cascader>
          </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品参数" name="1">
        <el-form-item v-for="(item, i) in manyparamsList" :key = 'i' :label="item.attr_name">
          <el-checkbox-group v-model="item.attr_vals" @change="CheckeditsChange">
            <el-checkbox v-for="(it, i1) in item.attr_vals" :label="it" border :key="i1"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <pre>{{paramsList}}</pre> -->
      </el-tab-pane>
      <el-tab-pane label="商品属性" name="2">
        <el-form-item v-for="item in onlyparamsList" :label="item.attr_name" :key="item.attr_id">
          <el-input v-model="item.attr_vals"></el-input>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="3">
        <!--action:上传地址  on-preview: 预览 on-remove：删除-->
        <el-upload action="http://127.0.0.1:8888/api/private/v1/upload"
          :on-preview="PreviewPicture"
          :on-remove="RemovePicture"
          list-type="picture"
          :headers="headerObj"
          :on-success="savePicPath">
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容" name="4">
        <quill-editor v-model="baseInfo.goods_introduce" />
        <el-button type="primary" @click="addgoods" class="addbtn">添加商品</el-button>
      </el-tab-pane>
    </el-tabs>
  </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="Previewvisible" width="50%" @close="Previewvisible = false" >
      <img :src="PicUrl" class="preimg">
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  created () {
    this.getCatalogList()
  },
  data () {
    return {
      Previewvisible: false,
      stepactive: '0',
      baseInfo: {
        goods_cat: [],
        // 图片临时路径
        pics: [],
        goods_number: 0,
        goods_weight: 0,
        goods_price: 0,
        goods_name: '',
        goods_introduce: '',
        attrs: []
      },
      // 表单验证规则
      baseInfoRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      // 分类列表
      CataList: [],
      // 级联属性
      params: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      // 选中的分类数组
      selectCataId: [],
      // 动态分类参数
      manyparamsList: [],
      // 静态分类参数
      onlyparamsList: [],
      // 选中的参数标签
      checkedit: [],
      // 图片上传请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      PicUrl: ''
    }
  },
  computed: {
    CataId () {
      if (this.baseInfo.goods_cat.length !== 3) {
        return null
      }
      return this.baseInfo.goods_cat[2]
    }
  },
  methods: {
    // 获取分类列表
    async getCatalogList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.CataList = res.data
      // console.log(this.CataList)
    },
    // 选中分类
    CataChange () {
      console.log(this.baseInfo.goods_cat)
      if (this.baseInfo.goods_cat.length !== 3) {
        this.baseInfo.goods_cat = []
      }
    },
    // 标签页切换
    beforeTabsleave (activeName, oldactiveName) {
      console.log(activeName)
      if (oldactiveName === '0' && this.baseInfo.goods_cat.length !== 3) {
        this.$message.error('请先选择分类！')
        return false
      }
    },
    // 获取分类参数
    async getParamsList () {
      // 访问动态参数
      if (this.stepactive === '1') {
        this.getParam('many')
      } else if (this.stepactive === '2') {
        this.getParam('only')
      }
    },
    // 访问参数
    async getParam (strsel) {
      const { data: res } = await this.$http.get(`categories/${this.CataId}/attributes`, { params: { sel: strsel } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.status)
      if (strsel === 'many') {
        res.data.forEach(item => {
          if (item.attr_vals.trim().length > 0) {
            item.attr_vals = item.attr_vals.split(' ')
          } else item.attr_vals = []
        })
        this.manyparamsList = res.data
      } else {
        this.onlyparamsList = res.data
      }
    },
    CheckeditsChange () {
      console.log(this.checkedit)
    },
    // 预览图片
    PreviewPicture (file) {
      // console.log(file)
      this.PicUrl = file.response.data.url
      this.Previewvisible = true
    },
    // 删除图片
    RemovePicture (file) {
      // console.log(file)
      const index = this.baseInfo.pics.findIndex(value => value === file.response.data.tmp_path)
      this.baseInfo.pics.splice(index, 1)
      // console.log(this.baseInfo.pics)
    },
    // 监听图片上传成功
    savePicPath (response) {
      this.baseInfo.pics.push({ pic: response.data.tmp_path })
      // console.log(this.baseInfo)
    },
    addgoods () {
      this.$refs.baseInfoRef.validate(async vaild => {
        if (!vaild) return this.$message({ type: 'info', message: '请填写必要项！' })
        // 处理分类
        const form = _.cloneDeep(this.baseInfo)
        form.goods_cat = form.goods_cat.join(',')
        // 处理参数
        this.manyparamsList.forEach(item => {
          const manyattr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          form.attrs.push(manyattr)
        })
        this.onlyparamsList.forEach(item => {
          const onlyattr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          form.attrs.push(onlyattr)
        })
        console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert{
  margin-bottom: 20px;
}
.el-steps{
  margin: 0 80px;
  margin-bottom: 50px;
}
.el-checkbox{
  margin: 0 5px 0 0 !important;
}
.preimg{
  width: 100%;
}
.addbtn{
  margin-top:20px;
}

</style>
